<?php
namespace app\console\model;


use think\facade\Request;
use think\facade\Route;
use think\Model;
use think\model\concern\SoftDelete;
use think\facade\Db;

class Privilege extends Base
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    protected $defaultSoftDelete = '0000-00-00 00:00:00';
//

    public static function onBeforeInsert($data)
    {
        $param = Request::param();
        if (self::checkCase($data->url)) {
            $data->parent_id = $data['parent_id'];
            $data->pri_name = $data['pri_name'] . '列表';
            $data->url = 'console/' . $data['url'] . '/index';
            //self::create(['parent_id' => $data['parent_id'],'pri_name' => $data['pri_name'].'列表','url' => Route::buildUrl('index')]);

        }
    }

    public static function onAfterInsert($data)
    {

        $param = Request::param();;

        Db::name('RolePri')->insert(['role_id'=>1,'pri_id'=>$data['id']]);
        if (self::checkCase($param['url'])) {
        Db::name('Privilege')->insert(['parent_id' => $data['id'],'pri_name' => '添加','url' => 'console/'.$param['url'].'/create','create_time' => date('Y-m-d H:i:s')]);
        Db::name('RolePri')->insert(['role_id'=>1,'pri_id'=>Db::name('Privilege')->getLastInsID()]);
        Db::name('Privilege')->insert(['parent_id' => $data['id'],'pri_name' => '修改','url' => 'console/'.$param['url'].'/update','create_time' => date('Y-m-d H:i:s')]);
        Db::name('RolePri')->insert(['role_id'=>1,'pri_id'=>Db::name('Privilege')->getLastInsID()]);
        Db::name('Privilege')->insert(['parent_id' => $data['id'],'pri_name' => '删除','url' => 'console/'.$param['url'].'/destory','create_time' => date('Y-m-d H:i:s')]);
        Db::name('RolePri')->insert(['role_id'=>1,'pri_id'=>Db::name('Privilege')->getLastInsID()]);
        Db::name('Privilege')->insert(['parent_id' => $data['id'],'pri_name' => '批量排序','url' => 'console/'.$param['url'].'/index_update','create_time' => date('Y-m-d H:i:s')]);
        Db::name('RolePri')->insert(['role_id'=>1,'pri_id'=>Db::name('Privilege')->getLastInsID()]);

            $top_parent = parentPath($param['parent_id'],'Privilege'); //不包含自己的上级;包不包含也没啥用 当前选中上级的顶级
            if(!empty($top_parent)){
                $top_id = current($top_parent)['id']; //二维数组 第一个ID
            }else{
                $top_id = $param['parent_id'];
            }
            $privilege =  Db::name('Privilege')->find($top_id);//把当前模块的(列表)url拼接到最顶级的url里;
            Db::name('Privilege')->where('id',$top_id)->update(['url'=>$privilege['url'].','.$param['url']]);
        }

    }

    protected static function onBeforeDelete($data)
    {
        $id_args =  sonPath(self::select(),$data['id'],true);

        (new self())->where('id','in',$id_args)->delete();
    }

    private static function checkCase($str)
    {

        if(preg_match('/^[A-Z]{1}/', $str,$data))
        {
            return true; //大写字母
        }
    }





}